#!/usr/bin/env python
# -*- coding:utf-8 -*-


# 输入：n x 4 的坐标list，每一行代表[起点， 终点， 宽， 高]
# 输出：n x 2 的栅格list，每一行代表[起点，终点]
def cord_to_grid(cord_pairs):
    grid_pairs = [] # 存储管道组的栅格坐标
    for pair in cord_pairs:
        start_point = pair[0]
        end_point  = pair[1]
        width = pair[2]
        height = pair[3]
        # 栅格x, y坐标由管道宽度决定，栅格z坐标由管道高度决定
        start_grid = [int(start_point[0]/width), int(start_point[1]/width), int(start_point[2]/height)]
        end_grid = [int(end_point[0]/width), int(end_point[1]/width), int(end_point[2]/height)]
        grid_pairs.append([start_grid,end_grid])
    return grid_pairs


# 输入：n x 2 的栅格list，每一行代表[起点，终点]；管道宽；管道高
# 输出：n x 4 的坐标list，每一行代表[起点， 终点， 宽， 高]
def grid_to_cord(grid_pairs, width, height):
    cord_pairs = [] # 存储管道组的栅格坐标
    for pair in grid_pairs:
        start_point = pair[0]
        end_point  = pair[1]
        # x, y坐标按管道宽度取栅格，z坐标按照管道高度取栅格
        start_grid = [start_point[0] * width, start_point[1] * width, start_point[2] * height]
        end_grid = [end_point[0] * width, end_point[1] * width, end_point[2] * height]
        cord_pairs.append([start_grid, end_grid, width, height])
    return cord_pairs

def get_average_error(origin_pairs, transform_pairs):
    loss = 0
    n = len(origin_pairs)
    for i in range(n):
        origin_pair = origin_pairs[i]
        transform_pair = transform_pairs[i]
        loss += (
            abs(origin_pair[0][0] - transform_pair[0][0])+
            abs(origin_pair[0][1] - transform_pair[0][1])+
            abs(origin_pair[0][2] - transform_pair[0][2])
            ) / 6
        loss += (
            abs(origin_pair[1][0] - transform_pair[1][0])+
            abs(origin_pair[1][1] - transform_pair[1][1])+
            abs(origin_pair[1][2] - transform_pair[1][2])
            ) / 6
    loss /= n
    return loss


if __name__ == "__main__":
    pairs = [
        [[56104.012409561, 108526.401082039, 56400.0], [56104.012409561, 105874.22212382, 56400.0], 1500.0, 500.0],
        [[56104.012409561, 105874.22212382, 56400.0], [61204.012409561, 105874.22212382, 56400.0], 1500.0, 500.0],
        [[61204.012409561, 105874.22212382, 56400.0], [61204.012409561, 97872.359470751, 56400.0], 1500.0, 500.0],
        [[61204.012409561, 97872.359470751, 56400.0], [74304.012409561, 97872.359470751, 56400.0], 1500.0, 500.0],
        [[74304.012409561, 97872.359470751, 56400.0], [74304.012409561, 93150.312199454, 56400.0], 1500.0, 500.0]
        ]
    print(pairs)
    print('\n')
    grids = cord_to_grid(pairs)
    print(grids)
    print('\n')
    cords = grid_to_cord(grids, 1500.0, 500.0)
    print(cords)
    print('\n')
    errorn = get_average_error(pairs, cords)
    print(errorn)
